package com.uchengwang.ui.cm_ui.uu.ui;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.OnHttpResultListener;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.image.ImageManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.BaseWhitTitleNoBackActivity;
import com.uchengwang.ui.cm_ui.uu.bean.XiangliaoBean;
import com.uchengwang.ui.cm_ui.uu.http.XiangliaoManager;
import com.uchengwang.ui.utils.DensityUtil;
import com.uchengwang.ui.utils.DialogUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import io.rong.imlib.model.Conversation;
import pl.droidsonroids.gif.GifImageView;

/**
 * Created by U城网 on 2018/4/16.
 * 享聊
 */

public class XiangliaoActivity extends BaseWhitTitleNoBackActivity implements View.OnClickListener{
    private RelativeLayout xiangliao;
    private int i=0;
    private int initLocation, previousLocation;//初始化位置  上次的位置(预防两次的位置相近)
    private int width, hegiht;

    private List<Integer> intLocation = new ArrayList<>();//{100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700};
    private Random random;
    private List<AnimatorSet> animatorSets = new ArrayList<>();
    private boolean isPause;//暂停的话 就不在更新动画
    private GifImageView xiangliao_gif_bottom;
    private ImageView xiangliao_gif, xiangliao_check;

    private MyHandler handler;

    private int page =1, totalPagers;
    private List<XiangliaoBean> xiangliaoBeans;//享聊用户的数据
    private boolean isCanHttp = true;//是否可以请求网络数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_xiangliao);
        titleBar.setVisibility(View.GONE);

        width = DensityUtil.getUtil().getScreenWidth(this);
        hegiht = DensityUtil.getUtil().getScreenHeight(this);

        int le = 100;
        do {
            intLocation.add(le);
            le +=50;
        }while (le < width -200);


        Log.d("jjf", "宽=="+width+"==高=="+hegiht);

        handler = new MyHandler(this);

        initView();

//        initDataView();
        addData();
    }

    private void initView(){
        xiangliao = (RelativeLayout) findViewById(R.id.xiangliao);
        xiangliao_gif = (ImageView) findViewById(R.id.xiangliao_gif);
//        xiangliao_gif.setBackgroundResource(R.drawable.gif_want_chat);

        ImageManager.getInstance().setRoundSize(0).loadImage(this, xiangliao_gif, R.drawable.image_xiangliao_bg, ImageManager.ImageType.ROUND);

//        xiangliao_gif_bottom = (GifImageView) findViewById(R.id.xiangliao_gif_bottom);
//        xiangliao_gif_bottom.setBackgroundResource(R.drawable.gif_want_chat_bottom);

        xiangliao_check = (ImageView) findViewById(R.id.xiangliao_check);
        xiangliao_check.setOnClickListener(this);
    }

    private void initDataView() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_xiangliao_item, null);
        ImageView qiqiu = view.findViewById(R.id.xiangliao_chat);
        ImageView head = view.findViewById(R.id.xiangliao_head);
        ImageView left_icon = view.findViewById(R.id.xiangliao_left_icon);
        ImageView right_icon = view.findViewById(R.id.xiangliao_right_icon);

        TextView xiangliao_name = view.findViewById(R.id.xiangliao_name);
        TextView xiangliao_rela = view.findViewById(R.id.xiangliao_rela);

        final XiangliaoBean b = xiangliaoBeans.get(i);

        qiqiu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UCommonUtil.getUtil().toChatActiviy(XiangliaoActivity.this, b.getUid(), Conversation.ConversationType.PRIVATE, b.getNickName());
                setPause();
            }
        });
        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.getUtils().showXLDialog(XiangliaoActivity.this, b, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String nameString = (!TextUtils.isEmpty(b.getRemarkName()) ? b.getRemarkName() : b.getNickName());
                        UCommonUtil.getUtil().toChatActiviy(XiangliaoActivity.this, b.getUid(), Conversation.ConversationType.PRIVATE, nameString);

                    }
                }, new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        DialogUtils.getUtils().cancel();
                        setStart();
                    }
                });
                setPause();

                greet(b.getUid());

            }
        });

        if (random == null){
            random = new Random();
        }

        do {
            initLocation = intLocation.get(random.nextInt(intLocation.size()));
        }while (initLocation == previousLocation);

        previousLocation = initLocation;


        Log.d("jjf", "心情气球=="+b.getEmotionType());
        if (b != null){
            ImageManager.getInstance().loadImage(this, head, b.getUserAvatar(), ImageManager.ImageType.CIRCLE);
            ImageManager.getInstance().loadImage(this, qiqiu, XiangliaoManager.getManager().getEmotionResId(b.getEmotionType()), ImageManager.ImageType.NARMOL);
            if (b.isFollow()){
                right_icon.setVisibility(View.VISIBLE);
                ImageManager.getInstance().loadImage(this, right_icon, R.drawable.icon_friend_sign, ImageManager.ImageType.NARMOL);
            }else {
                right_icon.setVisibility(View.GONE);
            }

            if (!TextUtils.isEmpty(b.getRemarkName())){
                xiangliao_name.setText(b.getRemarkName());
            }else {
                xiangliao_name.setText(b.getNickName());
            }

            if (b.getRelation() >0){
                xiangliao_rela.setText("+"+b.getRelation()+"");
            }

            if (b.getUniId() ==UChengApplication.myUniId){
                left_icon.setVisibility(View.VISIBLE);
                ImageManager.getInstance().loadImage(this, left_icon, R.drawable.ic_school, ImageManager.ImageType.NARMOL);
            }else {
                left_icon.setVisibility(View.GONE);
            }

        }

//        ImageManager.getInstance().loadImage(this, head, resIds[random.nextInt(resIds.length)], ImageManager.ImageType.CIRCLE);
//        ImageManager.getInstance().loadImage(this, qiqiu, bgs[random.nextInt(bgs.length)], ImageManager.ImageType.NARMOL);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.leftMargin = initLocation;

        xiangliao.addView(view, layoutParams);
        animo(view);
        i++;

        handler.sendEmptyMessageDelayed(0, 2500);
    }

    //加载view动画
    private void animo(final View view){
        ObjectAnimator moveIn = ObjectAnimator.ofFloat(view, "translationY", hegiht, -500f);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1, 0.3f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1, 0.3f);

        final AnimatorSet animSet = new AnimatorSet();
        animSet.play(moveIn).with(scaleX).with(scaleY);
        animSet.setInterpolator(new DecelerateInterpolator());//匀速插值器
        animSet.setDuration(15000);
        animSet.start();
        animatorSets.add(animSet);

        animSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }

            @Override

            public void onAnimationEnd(Animator animation) {
                if (animatorSets != null && animatorSets.size() >0 && animSet != null){
                    animatorSets.remove(animSet);
                    animSet.removeAllListeners();
                    xiangliao.removeView(view);
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        DialogUtils.getUtils().cancel();
        setStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        setPause();
    }

    //全部暂停动画
    private void setPause(){
        if (!isPause){
            handler.removeMessages(0);
            isPause = true;
            if (animatorSets != null && animatorSets.size() >0){
                for (AnimatorSet set : animatorSets){
                    if (set != null){
                        set.pause();
                    }
                }
            }
        }
    }

    //全部开始动画
    private void setStart(){
        if (isPause){
            isPause = false;
            if (animatorSets != null && animatorSets.size() >0){
                for (AnimatorSet set : animatorSets){
                    if (set != null){
                        set.resume();
                    }
                }
            }
            handler.sendEmptyMessage(0);
        }
    }

    //请求网络添加数据
    private void addData(){
        MapRequest map = new MapRequest();
        map.put(BaseConfig.SEX, UChengApplication.sex ==0 ? 1: 0);
        map.put(BaseConfig.PAGE, page);
        map.put(BaseConfig.PERPAGE, 50);
        XiangliaoManager.getManager().getUsers(this, map, new OnHttpResultListener<XiangliaoBean>() {
            @Override
            public void onResult(int status, String msg, int total, List<XiangliaoBean> list) {
                isCanHttp = true;
                totalPagers =total;
                if (list != null && list.size() >0){
                    page++;
                    if (xiangliaoBeans ==null){
                        xiangliaoBeans = list;
                    }else {
                        xiangliaoBeans.addAll(list);
                    }
                    handler.removeMessages(0);//将之前的handler消息给去掉
                    handler.sendEmptyMessage(0);
                }
            }
        });
    }

    //点击头像打招呼
    private void greet(long uid){
        XiangliaoManager.getManager().greet(this, uid, new OnResultListener() {
            @Override
            public void onResult(int stutas, String msg, int total, String data) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.xiangliao_check://跳转到享聊记录界面
                setPause();
                Intent intent = new Intent(this, XiangliaoRelationActivity.class);
                startActivity(intent);

                break;
        }
    }

    private static class MyHandler extends Handler{
        private WeakReference<XiangliaoActivity> weakReference;
        public MyHandler (XiangliaoActivity activity){
            weakReference = new WeakReference<XiangliaoActivity>(activity);

        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    XiangliaoActivity activity = weakReference.get();

                    if (!activity.isPause){
                        if(activity.xiangliaoBeans != null && activity.i <activity.xiangliaoBeans.size()){
                            activity.initDataView();
//                            activity.i++;
                            if ((activity.xiangliaoBeans.size() -activity.i) <10){
                                if (activity.isCanHttp && activity.page <= activity.totalPagers){
                                    activity.addData();//当剩余的数量小于10个时, 请求网络
                                    activity.isCanHttp = false;
                                }
                            }
                        }
                    }
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null){
            handler.removeCallbacksAndMessages(null);
        }
        animatorSets.clear();
        animatorSets = null;
    }
}
